package com.cw.frame.codegen;

import org.apache.commons.lang3.StringUtils;

import com.cw.frame.codegen.engine.TemplateEngine;
import com.cw.frame.codegen.engine.VelocityTemplateEngine;
import com.cw.frame.codegen.parameter.ParamContext;
import com.cw.frame.codegen.parameter.ParamContextFactory;
import com.cw.frame.codegen.parameter.ParamContextFactory4EntityClassImpl;
import com.cw.frame.codegen.parameter.ParamContextFactory4JdbcImpl;
import com.cw.jeeyt.common.enums.EnumGenerateCodeType;

/**
 * The main class to generate sample code.
 *
 * @author chenw
 */
public class Main {

    /**
     * The main method to create source file according to the templates.
     *
     * @param args
     */
    public static void main(String[] args) {
        try {
            new Main().createSourceFiles();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createSourceFiles() throws Exception {
        ParamContext paramContext = getParamContextFactory().create(EnumGenerateCodeType.JDBC.getCode());
        if (paramContext == null) {
            System.err.println("Error: can't create param context!");
            throw new Exception("Error: can't create param context!");
        }

        TemplateEngine templateEngine = getTemplateEngine();

        JavaFileGenerator javaFileGenerator = new JavaFileGenerator();
        javaFileGenerator.setTemplateEngine(templateEngine);
        javaFileGenerator.generate(paramContext);

        PageFileGenerator pageFileGenerator = new PageFileGenerator();
        pageFileGenerator.setTemplateEngine(templateEngine);
        pageFileGenerator.generate(paramContext);
    }

    private ParamContextFactory getParamContextFactory() {
        Configuration configuration = Configuration.getDefault();
        if (!StringUtils.isEmpty(configuration.getTableNames())) {
            return new ParamContextFactory4JdbcImpl();
        }
        return new ParamContextFactory4EntityClassImpl();
    }

    private TemplateEngine getTemplateEngine() {
        return new VelocityTemplateEngine();
    }

}
